import store from "@/store";

const install = (Vue, vm) => {
	// 此为自定义配置参数，具体参数见上方说明
	Vue.prototype.$xt.http.setConfig({
		showLoading: true,
		loadingTime: 500,
	});
	// 请求拦截，配置Token等参数
	Vue.prototype.$xt.http.interceptor.request = (config) => {
		let baseUrl = uni.getStorageSync("baseUrl")
		store.commit("showLoading", true);
		
		Vue.prototype.$xt.http.setConfig({
			baseUrl: baseUrl,
		})
		const token = uni.getStorageSync('token');
		if (!config.header.noToken) {
			config.header.token = token
		}
		
		// #ifdef APP-PLUS
		config.header.platform = "android"
		const version = vm.$xt.appVersion
		config.header.version = version
		// #endif
		// #ifdef MP
		// config.header.platform = "miniprogram"
		// #endif
		if (!config.header.noToken && !token) {
			store.commit("showLoading", false);
			return false
		}
	}
	
	const compareInt = function(arr1,arr2){
	    let len = Math.max(arr1.length,arr2.length)
	    while(arr1.length < len) arr1.push(0)
	    while(arr2.length < len) arr2.push(0)
	    for(let i = 0; i < len; i++){
	        if(arr1[i] > arr2[i]) return 1
	        else if(arr1[i] < arr2[i]) return -1
	    }
	    return 0
	}
	const compareVersion = function(version1, version2) {
	    let v1 = version1.split('.')
	    let v2 = version2.split('.')
	    v1 = v1.map((item)=>Number.parseInt(item))
	    v2 = v2.map((item)=>Number.parseInt(item))
	    return compareInt(v1,v2)
	};
	
	let appUpdate = function(isUpdate) {
		return vm.$xt.get('/doctor/versions/android/refresh/doctor').then(res=>{
			let data = res.data
			if(data && !isUpdate){
				let version = data.version,
					localVersion = vm.$xt.appVersion,
					packageUrl = data.packageUrl,
					message = encodeURI(data.updates),
					forced = data.forced
				let result = compareVersion(version, localVersion)
				let path = "/components/full-modal/full-modal"
				if (result == 1) {
					// 需要更新
					let pages = getCurrentPages(),
						page = pages[pages.length - 1],
						route = page.route
					if (route.indexOf(path) < 0) {
						// 当前路径是不在弹窗
						uni.navigateTo({
							url: path + `?type=update&forced=1&message=${message}&url=${packageUrl}`,
							animationType: 'fade-in'
						})
					}
				}
			}
		}).catch(res=>{
			// isUpdate = false
			// console.log(res)
		}).finally(() => {
			isUpdate = false
		});
	}
	
	let isRefreshing = false
	let requests = []
	let isUpdate = false
	// 响应拦截，判断状态码是否通过
	Vue.prototype.$xt.http.interceptor.response = (res, options) => {
		uni.stopPullDownRefresh()
		store.commit("showLoading", false);
		if (res.code == 0) {
			return res
		}  else if (res.code == 401) {
			vm.$u.toast("登录失效，请重新登录", 1000);
			vm.$xt.util.clearAll()
			setTimeout(() => {
				vm.$u.route({
					url: '/pages/welcome/login',
					type: 'reLaunch'
				})
			}, 1000)
		} else {
			return false;
		}
	}	
}

export default {
	install
}
